<template>
  <div class="upload-file-container">
    <!-- 文件列表区域 -->
    <div v-if="localFilePath" class="file-item">
      <div class="file-info">
        <el-icon class="file-icon"><Document /></el-icon>
        <div class="file-details">
          <div class="file-name" :title="fileName">{{ fileName }}</div>
          <div class="file-meta">
            <span class="file-size">{{ fileSize }}</span>
            <span class="file-path" :title="localFilePath">{{ formattedPath }}</span>
          </div>
        </div>
      </div>
      <div class="file-actions">
        <el-button
          type="text"
          icon="Download"
          size="small"
          @click="handleDownload"
          v-if="canDownload"
        >{{ t('sys.components.upload.download') }}</el-button>
        <el-button
          type="text"
          icon="Delete"
          size="small"
          @click="handleDelete"
        >{{ t('sys.components.upload.delete') }}</el-button>
      </div>
    </div>

    <!-- 上传区域 -->
    <div v-else class="upload-area" @click="handleUploadClick">
      <div class="upload-text">{{ t('sys.components.upload.clickToUploadFile') }}</div>
      <input
        ref="fileInput"
        type="file"
        :accept="accept"
        class="file-input"
        @change="handleFileChange"
      />
    </div>

    <!-- 错误提示 -->
    <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, defineProps, defineEmits, computed } from 'vue';
import { ElButton, ElIcon, ElLoading } from 'element-plus';
import { Document, UploadFilled, Download, Delete } from '@element-plus/icons-vue';
import { uploadSingleFileApi } from '@/api/upload/upload';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();

// 定义props
const props = defineProps({
  filePath: {
    type: String,
    default: '',
    required: false
  },
  accept: {
    type: String,
    default: '',
    required: false
  },
  fileSizeLimit: {
    type: Number,
    default: 10,
    required: false
  }
});

// 定义事件
const emit = defineEmits(['update:filePath', 'change']);

// 本地状态
const localFilePath = ref<string>(props.filePath);
const uploadLoading = ref<boolean>(false);
const errorMessage = ref<string>('');
const fileInput = ref<HTMLInputElement | null>(null);
const fileInfo = ref<{name: string, size: number}>({name: '', size: 0});

// 监听props变化，同步到本地状态
watch(
  () => props.filePath,
  (newVal) => {
    localFilePath.value = newVal;
    setTimeout(()=>{
      parseFilePath(newVal);
    },10)
  },
  { immediate: true }
);

// 解析文件路径获取文件名和大小
const parseFilePath = (path: string) => {
  if (!path) {
    fileInfo.value = {name: '', size: 0};
    return;
  }
  // 这里假设路径格式为"/uploads/2023/10/filename.ext"，实际解析逻辑需根据后端返回格式调整
  const parts = path.split('/');
  fileInfo.value.name = parts[parts.length - 1] || '';
  // 文件大小需要从后端获取，这里暂时模拟
  fileInfo.value.size = 0;
};

// 计算属性
const fileName = computed(() => fileInfo.value.name);
const fileSize = computed(() => {
  if (!fileInfo.value.size) return '';
  return formatFileSize(fileInfo.value.size);
});
const formattedPath = computed(() => {
  if (!localFilePath.value) return '';
  // 简化显示路径，只保留最后两级目录
  const parts = localFilePath.value.split('/');
  if (parts.length <= 2) return localFilePath.value;
  return `.../${parts.slice(-2).join('/')}`;
});
const canDownload = computed(() => !!localFilePath.value);

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
};

// 触发文件选择
const handleUploadClick = () => {
  if (uploadLoading.value) return;
  fileInput.value?.click();
};

// 处理文件选择
const handleFileChange = async (e: Event) => {
  const target = e.target as HTMLInputElement;
  if (!target.files || target.files.length === 0) return;

  const file = target.files[0];
  // 文件大小验证
  if (props.fileSizeLimit && file.size > props.fileSizeLimit * 1024 * 1024) {
    errorMessage.value = t('sys.components.upload.fileSizeLimit', { size: props.fileSizeLimit });
    return;
  }

  await handleFileUpload(file);

  // 重置input值，允许重复上传同文件
  target.value = '';
};

// 处理文件上传
const handleFileUpload = async (file: File) => {
  uploadLoading.value = true;
  errorMessage.value = '';
  fileInfo.value = {name: file.name, size: file.size};

  try {
    const response = await uploadSingleFileApi(file);
    console.log(response);
    if (response && response.code === 0) {
      const filePath = response.data.fullPath;
      localFilePath.value = filePath;
      // 触发事件通知父组件
      emit('update:filePath', filePath);
      emit('change', filePath);
    } else {
      throw new Error(response.data?.message || t('sys.components.upload.uploadFail'));
    }
  } catch (error) {
    errorMessage.value = error instanceof Error ? error.message : t('sys.components.upload.uploadFail');
    console.error('文件上传失败:', error);
  } finally {
    uploadLoading.value = false;
  }
};

// 处理文件删除
const handleDelete = () => {
  localFilePath.value = '';
  fileInfo.value = {name: '', size: 0};
  emit('update:filePath', '');
  emit('change', '');
};

// 处理文件下载
const handleDownload = () => {
  if (!localFilePath.value) return;
  // 这里需要后端提供下载接口
  window.open(localFilePath.value, '_blank');
};
</script>

<style scoped lang="scss">
.upload-file-container {
  width: 100%;
  min-height: 60px;
  position: relative;
}

.file-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  background-color: #f9fafb;
  transition: border-color 0.3s;

  &:hover {
    border-color: #409eff;
  }
}

.file-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.file-icon {
  color: #409eff;
  margin-right: 12px;
  font-size: 20px;
}

.file-details {
  overflow: hidden;
}

.file-name {
  font-size: 14px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 4px;
}

.file-meta {
  font-size: 12px;
  color: #666;
  display: flex;
  align-items: center;
  gap: 12px;
}

.file-path {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #999;
}

.file-actions {
  display: flex;
  gap: 8px;
}

.upload-area {
  width: 100%;
  height: 100px;
  border: 1px dashed #ccc;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
 justify-content: center;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    border-color: #409eff;
    background-color: #f0f7ff;
  }
}

.upload-icon {
  color: #409eff;
  margin-bottom: 8px;
}

.upload-text {
  color: #606266;
  font-size: 14px;
}

.file-input {
  display: none;
}

.upload-loading {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.error-message {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 5px;
  text-align: left;
}
</style>
